import Vue from 'vue'
import VueRouter from 'vue-router'
import AdminTemplate from '../views/layout/AdminTemplate.vue'

Vue.use(VueRouter)

const routes = [{ //首页
    path: '/',
    name: 'Home',
    redirect: "/admin/Home", // 重定向到管理首页
    // 当访问首页时 会跳转到 管理页面
    // component: Home
  },
  {
    path: '/vuex',
    name: 'vuex',
    component: () => import('../views/vuex'),
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/login.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/login/register.vue')
  },
  {
    path: '/admin',
    name: "Admin",
    component: AdminTemplate,
    children: [
      //首页
      {
        path: "home",
        name: "AdminHome",
        component: () => import('../views/Home.vue')
      },
      //题库管理
      {
        path: "questionBank",
        name: "QuestionBank",
        component: () => import('../views/question/QuestionBank.vue'),
        children: [{ //列表
            path: "list",
            name: "QuestionBankList",
            component: () => import('../views/question/List.vue'),
          },
          { // 新增试题
            path: "create",
            name: "QuestionBankCreate",
            component: () => import('../views/question/Create.vue'),
          },
        ]
      },
      {
        path: "students",
        name: "Students",
        component: () => import('../views/student/Students.vue')
      },
      {
        path: "subject",
        name: "Subject",
        component: () => import('../views/subject/Subject.vue')
      },
      {
        path: "testPaper",
        name: "TestPaper",
        component: () => import('../views/test/TestPaper.vue')
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


router.beforeEach((to, from, next) => {
  console.log(to, from);
  if(/^\/admin\/*/.test(to.path)) {
    if (localStorage.getItem("userInfo")) {
      //如果已经登录，可以继续访问
      next()
    } else {
      //没有登录就跳转到登录页面
      alert("您还没有登录，请先登录！")
      next("/login");
    }
  } else{
    next()
  }
  
})

export default router